#include "videoWidget.h"
#include <spdlog/spdlog.h>
#include <memory>
#include "ffmVideoReader.h"

using namespace std;

VideoWidget::VideoWidget(QWidget* parent)
    : QWidget{parent} {
    videoReader_ = new FfmVideoReader();
}

VideoWidget::~VideoWidget() {
    if (videoReader_) {
        delete videoReader_;
    }
}

void VideoWidget::setRects(QVector<QRect>& rects) {
    std::unique_lock<std::mutex> lk(rectMutex_);
    rects_ = rects;
    lk.unlock();
}

void VideoWidget::refresh() {
    this->update();
}

void VideoWidget::paintEvent(QPaintEvent* event) {
    QPainter painter(this);
    painter.drawImage(rect(), image_, image_.rect());
}

void VideoWidget::open(const char* videoPath) {
    path_ = videoPath;
    videoReader_->open(videoPath);

    videoWidth = videoReader_->width;
    videoHeight = videoReader_->height;

    if (!widgetTh_) {
        widgetTh_ = new std::thread([this]() {
            isPlaying = true;
            while (isPlaying) {
                auto img = videoReader_->pop();
                if (nullptr == img) {
                    break;
                }

                image_ = QImage(img->getData(), videoReader_->width, videoReader_->height, QImage::Format_RGB888);
                // QMetaObject::invokeMethod(this, "refresh", Qt::QueuedConnection, Q_ARG(QImage, image));
                QMetaObject::invokeMethod(this, "refresh", Qt::QueuedConnection);

                videoReader_->stay();
            }
        });
    }
}

void VideoWidget::stop() {
    videoReader_->close();
    isPlaying = false;
    if (widgetTh_) {
        widgetTh_->join();
        delete widgetTh_;
        widgetTh_ = nullptr;
    }
}
